package me.itsoo.elasticbatis.datasource;

import lombok.Getter;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.util.Properties;

/**
 * DataSourceFactory
 *
 * @author zhangxy4
 * @version 0.0.1
 * @since 2025/4/7
 */
@Getter
public class DataSourceFactory {
    private static final String DEFAULT_HOSTNAME = "localhost";
    private static final String DEFAULT_PORT = "9200";
    private static final String DEFAULT_SCHEME = "http";

    private static final String DEFAULT_KEEP_ALIVE_MILLIS = "3000000";
    private static final String DEFAULT_CONNECT_TIMEOUT = "1000";
    private static final String DEFAULT_SOCKET_TIMEOUT = "30000";

    private String hostname;
    private int port;
    private String scheme;

    private String username;
    private String password;

    private int keepAliveMillis;
    private int connectTimeout;
    private int socketTimeout;

    public void setProperties(Properties props) {
        this.hostname = props.getProperty("hostname", DEFAULT_HOSTNAME);
        this.port = Integer.parseInt(props.getProperty("port", DEFAULT_PORT));
        this.scheme = props.getProperty("scheme", DEFAULT_SCHEME);

        this.username = props.getProperty("username");
        this.password = props.getProperty("password");

        this.keepAliveMillis = Integer.parseInt(props.getProperty("keepAliveMillis", DEFAULT_KEEP_ALIVE_MILLIS));
        this.connectTimeout = Integer.parseInt(props.getProperty("connectTimeout", DEFAULT_CONNECT_TIMEOUT));
        this.socketTimeout = Integer.parseInt(props.getProperty("socketTimeout", DEFAULT_SOCKET_TIMEOUT));
    }

    @SuppressWarnings("deprecation")
    public RestHighLevelClient getDataSource() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        return new RestHighLevelClient(RestClient.builder(new HttpHost(hostname, port, scheme))
                .setHttpClientConfigCallback(t -> {
                    t.setDefaultCredentialsProvider(credentialsProvider);
                    t.setKeepAliveStrategy((response, context) -> keepAliveMillis);
                    return t;
                })
                .setRequestConfigCallback(t -> {
                    t.setConnectTimeout(connectTimeout);
                    t.setSocketTimeout(socketTimeout);
                    return t;
                }));
    }
}
